package net.dgg.zz.production.distribution.service;

import net.dgg.framework.tac.utils.idutil.DggKeyWorker;
import net.dgg.iboss.base.util.DateUtil;
import net.dgg.iboss.base.util.DesUtil;
import net.dgg.tmd.foundation.platform.session.SessionManager;
import net.dgg.tmd.foundation.platform.user.entity.UserEntity;
import net.dgg.tmd.foundation.platform.user.service.UserService;
import net.dgg.zz.common.base.service.BaseService;
import net.dgg.zz.common.constant.ScNoteType;
import net.dgg.zz.common.constant.ScProductConstant;
import net.dgg.zz.common.entity.CustomerRecord;
import net.dgg.zz.common.entity.Node;
import net.dgg.zz.common.service.CommonMangerExtService;
import net.dgg.zz.common.service.CommonService;
import net.dgg.zz.common.service.FlowService;
import net.dgg.zz.common.systemRecord.entity.SystemRecord;
import net.dgg.zz.common.systemRecord.service.SystemRecordService;
import net.dgg.zz.common.utils.DateUtils;
import net.dgg.zz.common.utils.MQMessageSendUtil;
import net.dgg.zz.common.utils.StringUtils;
import net.dgg.zz.production.entity.ProductOrder;
import net.dgg.zz.production.entity.ProductTimeStatus;
import net.dgg.zz.production.inProcess.dao.ProductNodeDao;
import net.dgg.zz.production.inProcess.dao.ProductNodeOperatingDao;
import net.dgg.zz.production.inProcess.dao.ProductOrderDao;
import net.dgg.zz.production.inProcess.dao.ProductTimeStatusDao;
import net.dgg.zz.production.inProcess.entity.ProductNode;
import net.dgg.zz.production.inProcess.entity.ProductNodeOperating;
import net.dgg.zz.production.inProcess.service.ZzInProcessService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.*;

@Service
public class DistributionService extends BaseService {

    /**
     * 生产订单dao
     */
    @Autowired
    private ProductOrderDao productOrderDao;
    /**
     * sessionmanager
     */
    @Autowired
    private SessionManager sessionmanager;

    @Autowired
    private UserService userservice;

    @Autowired
    protected DesUtil desUtil;
    /**
     * 注册接口
     */
    @Autowired
    private CommonMangerExtService commonMangerExtService;

    /**
     * 操作记录表
     */
    @Autowired
    private SystemRecordService systemRecordService;

    /**
     * 超期表
     */
    @Autowired
    private ProductTimeStatusDao productTimeStatusDao;

    @Autowired
    private CommonService commonService;
    @Autowired
    private ZzInProcessService zzInProcessService;
    @Autowired
    private ProductNodeOperatingDao productNodeOperatingDao;
    @Autowired
    private ProductNodeDao productNodeDao;
    @Autowired
    private FlowService flowService;
    @Autowired
    private UserService userService;


    /**
     * 查询多有待分配列表
     *
     * @param param
     * @return
     */
    @SuppressWarnings("unchecked")
    public List<Map> findAllWithPage(Map param) {
        param.put("SC_TO_RECEIVE_XDDJS", ScProductConstant.SC_TO_RECEIVE_XDDJS);
        param.put("SC_ORDER_BACK_TO_ALLOT", ScProductConstant.SC_ORDER_BACK_TO_ALLOT);

        //待分配页面，查询全部订单处于待分配的订单
        //待分配页面，查询
//        UserEntity userEntity = sessionmanager.getCurrentUser();
//        Map map = commonMangerExtService.findBusDeptById(userEntity.getOrgId());
        //        if (null != map) {
//            param.put("deptId", map.get("id"));
//        } else {
//            param.put("deptId", 0);
//        }

        if (null != param.get("customerPhone")) {
            param.put("customerPhone", desUtil.encrypt(param.get("customerPhone").toString()));
        }
        if (null == param.get("statusArr") || param.get("statusArr").equals(ScProductConstant.SC_TO_RECEIVE_XDDJS)) {
            param.put("cday", "cday");//判断是否是今日待分配标识
            param.put("statusArr", ScProductConstant.SC_TO_RECEIVE_XDDJS);
        }

        if (null == param.get("orderColumn")) {
            param.put("orderDir", "desc");//排序方向
            param.put("orderColumn", "t.create_time");//排序的列
        }
        return productOrderDao.findWaitDistributionAllWithPage(param);
    }

    /**
     * 根据id查询生产订单信息
     *
     * @param id 生产订单id
     * @return
     */
    public ProductOrder selectByPrimaryKey(Long id) {
        return productOrderDao.selectByPrimaryKey(id);
    }

    /**
     * 订单分配
     *
     * @param param 参数信息
     * @return
     */
    @SuppressWarnings("unchecked")
    @Transactional
    public String distributionProductOrder(Map param) {
        UserEntity currentUser = sessionmanager.getCurrentUser();//当前操作人
        Long id = Long.parseLong(param.get("id").toString());
        String allotWay = param.get("allotWay").toString();//分配方式
        ProductOrder order = productOrderDao.selectByPrimaryKey(id);
        ProductTimeStatus timestatus = productTimeStatusDao.selectByPrimaryKey(order.getId());
        //保存节点开始结束时间
        Date nodeStartTime = null;
        Date nodeEndTime = null;
        //判断当前订单的分配方式 如果是部门分配需要重新计数超期时间，其他分配方式从超期计算表中取
        if("分配" != timestatus.getNodeName()){
            nodeStartTime = order.getCreateTime();
            if(!StringUtils.isEmpty(order.getFlowContent())){
                //新流程
                List<Node> nodelist = flowService.getNode(id);
                if (nodelist.size() == 0) {
                    return "未配置流程！";
                }
                Node newNode = flowService.queyNodeListByName("分配", order.getId());
                if(null != newNode.getName()) {
                    nodeEndTime = commonService.getDateFromStartByType(null == order.getLatestEndNodeTime() ? order.getUpdateTime() : order.getLatestEndNodeTime(),
                            (int) Math.ceil((double)newNode.getHandleDate() / 24), (long) Math.ceil((double)newNode.getHandleDate() / 24) * 24 * 3600*1000,
                            newNode.getIsNaturalorWorkday());
                    nodeEndTime =  DateUtils.getDate(DateUtils.dateString(nodeEndTime,"yyyy-MM-dd"),"yyyy-MM-dd");
                }else{
                    nodeEndTime = commonService.getDateFromStartByType(order.getCreateTime(),
                            1,  24l * 3600*1000,
                            1);
                    nodeEndTime =  DateUtils.getDate(DateUtils.dateString(nodeEndTime,"yyyy-MM-dd"),"yyyy-MM-dd");
                }
            }else{
                //老流程默认1个工作日
                nodeEndTime = commonService.getDateFromStartByType(order.getCreateTime(),
                        1,  24l * 3600*1000,
                        1);
                nodeEndTime =  DateUtils.getDate(DateUtils.dateString(nodeEndTime,"yyyy-MM-dd"),"yyyy-MM-dd");
            }
        }else {
            nodeStartTime = timestatus.getNodeStartTime();
            nodeEndTime = timestatus.getNodeEndTime();
        }
        int a = DateUtils.compare_date(new Date(), nodeEndTime);
        if (!order.getStatus().equals(ScProductConstant.SC_TO_RECEIVE_XDDJS) && !order.getStatus().equals(ScProductConstant.SC_ORDER_BACK_TO_ALLOT)
                && !order.getStatus().equals(ScProductConstant.SC_ORDER_WAIT_ALLOT)) {//如果当前状态不是待分配状态或者事业部移交待分配
            //在待接收状态可以部门分单
            if(StringUtils.isEmpty(param.get("type"))){
                return "当前订单状态已改变，不能进行分配";
            }
        }
        if(!StringUtils.isEmpty(order.getFlowContent())) {
            //获取流程节点
            List<Node> nodelist = flowService.getNode(id);
            if (nodelist.size() == 0) {
                return "未配置流程！";
            }
            Node finishNode = flowService.queyNodeListByName("分配", order.getId());
            if (null == timestatus.getNodeEndTime()) {
                Date newDate = null;
                //获取当前节点的配置的计算出的超期时间
                newDate = commonService.getDateFromStartByType(new Date(),
                            (int) Math.ceil(finishNode.getHandleDate() / 24), (long) Math.ceil((double)finishNode.getHandleDate() / 24) * 24 * 3600*1000,
                            finishNode.getIsNaturalorWorkday());
                timestatus.setNodeEndTime(newDate);
            }
            if (a == 1) {
                if ((null == order.getPunishStatus() || 0 == order.getPunishStatus()) && null != timestatus.getNodeEndTime() && finishNode.getIsPunish()==1) {
                    Map currentMap = this.commonMangerExtService.findOrg(currentUser.getOrgId());
                    if (null != currentMap) {
                        order.setFlowUserId(currentUser.getId());
                        order.setFlowUserName(currentUser.getRealName().concat(currentUser.getLoginName()));
                        order.setFlowUserOrgId(Long.valueOf(currentMap.get("id").toString()));
                        order.setFlowUserOrgName(currentMap.get("name").toString());
                        Integer code = zzInProcessService.nodeTimeOutPunish(order, finishNode, timestatus);
                        if (code == 0) {
                            if("成都资质事业部".equals(order.getProductOrgName())){
                                //发送扣罚消息
                                try {//不让影响其他功能
                                    List<UserEntity> users = new ArrayList<>();
                                    //扣罚人
                                    UserEntity user = userService.findUserById(order.getFlowUserId());
                                    users.add(user);
                                    //1.生产订单节点奖罚：您好，{生产订单编号}{客户名称}{订单产品}，xx节点超期产生扣罚，请查看确认。
                                    String msg[] = new String[]{order.getScProductOrderNo(),order.getCustomerName(),order.getProductName(),finishNode.getName()};
                                    commonService.sendMsgByAsynchronous(users, msg, "ZZSC_NODE_PUNISH_ALERT");//匹配模板
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }

                }
            }
            Node node = new Node();
            if (nodelist.size() > 0) {
                node = flowService.queyNodeListByName("接单", order.getId());
                param.put("currentNodeId", node.getId());
                param.put("currentNodeName", node.getName());
            }
            //写入下个节点信息
                long currentTime = System.currentTimeMillis();
                Date date = new Date(currentTime);
                Integer hours = 0;
                if (null != node) {
                    timestatus.setNodeId(node.getId().toString());
                    timestatus.setNodeName(node.getName());
                    hours = node.getHandleDate();
                    timestatus.setNodeProcessTimeType(node.getIsNaturalorWorkday());
                    timestatus.setNodeStartTime(date);
                    long millisecond = 0;
                    long Days = (long) Math.ceil((double)node.getHandleDate() / 24);
                    if (hours > 0) {
                        millisecond = Days * 24 * 3600*1000;
                    }
                    Date currentDate = null;
                        //获取当前节点的配置的计算出的超期时间
                        currentDate = commonService.getDateFromStartByType(date,
                                (int) Math.ceil((double)node.getHandleDate() / 24), millisecond,
                                node.getIsNaturalorWorkday());
                        currentDate = DateUtils.getDate(DateUtils.dateString(currentDate,"yyyy-MM-dd"),"yyyy-MM-dd");
                    timestatus.setNodeEndTime(currentDate);
                    timestatus.setNodeProcessTime((int) Math.ceil((double)hours / 24));
                    timestatus.setNodeSuspendMillisecond(millisecond);
                    timestatus.setReceiveEndTime(currentDate);
                }
        }
        //写入下一个节点
        if(StringUtils.isEmpty(order.getFlowContent())){
            List<ProductNode> nodelist = zzInProcessService.queyNodeList(order.getNodeFlowId());
            for (ProductNode scProductNode : nodelist) {
                if (null != scProductNode.getName() && !"".equals(scProductNode.getName()) && "接单".equals(scProductNode.getName())) {
                    param.put("currentNodeId", scProductNode.getId());
                    param.put("currentNodeName", scProductNode.getName());
                    break;
                }
            }

        }


        Long receiverId = Long.parseLong(param.get("receiverId").toString());//分配人员id
        UserEntity userEntity = userservice.findUserById(receiverId);//查询接收人
        if (null == userEntity) {
            return "分配失败,未查询到接收人信息";
        }
        Map map = this.commonMangerExtService.findOrg(userEntity.getOrgId());
        if (null != map) {
            if (allotWay.equals(ScProductConstant.ALLOT_TO_PRODUCT_USER)) {//分配给负责人
                param.put("productUserId", userEntity.getId());
                param.put("productUserName", userEntity.getRealName() + userEntity.getLoginName());
                param.put("productUserOrgId", map.get("id"));
                param.put("productUserOrgName", map.get("name"));
            }else if(allotWay.equals(ScProductConstant.ALLOT_TO_PRODUCT_DEPT)){//分配给部门负责人
                param.put("deptHeadId", receiverId);
                param.put("deptHeadName", userEntity.getRealName() + userEntity.getLoginName());
                param.put("deptHeadOrgId", map.get("id"));
                param.put("deptHeadOrgName", map.get("name"));
            }
            param.put("receiverId", userEntity.getId());
            param.put("receiverName", userEntity.getRealName() + userEntity.getLoginName());
            param.put("receiverOrgId", map.get("id"));
            param.put("receiverOrgName", map.get("name"));
            //为了保证异常订单正常工作, 分配的时候把流程人员写进去
            param.put("flowUserId", userEntity.getId());
            param.put("flowUserName", userEntity.getRealName() + userEntity.getLoginName());
            param.put("flowUserOrgId", map.get("id"));
            param.put("flowUserOrgName", map.get("name"));
            order.setFlowUserId(userEntity.getId());
            order.setFlowUserName(userEntity.getRealName() + userEntity.getLoginName());
            param.put("allotWay", allotWay);//分配方式
            param.put("allotUserId", currentUser.getId());
            param.put("allotUserName", currentUser.getRealName() + currentUser.getLoginName());
            param.put("allotUserOrgId", currentUser.getId());
            param.put("allotUserOrgName", map.get("name"));
            param.put("allotDate", new Date());//分配时间
            // 如果无需办理直接进入完结列表
            if(!StringUtils.isEmpty(order.getFlowContent())) {
                List<Node> nodelist1 = flowService.getNode(id);
                if (param.containsKey("isNeedDispose") && "1".equals(param.get("isNeedDispose").toString())) {
                    param.put("status", ScProductConstant.SC_ORDER_OVER);//完结
                    if (nodelist1.size()>0) {
                        for (Node node1 : nodelist1) {
                            if ("完结".equals(node1.getName())) {
                                param.put("latestEndNodeId", node1.getId());
                                param.put("latestEndNodeName", node1.getName());
                                param.put("latestEndNodeTime", new Date());//设置最新更新节点时间
                                param.put("completedTime", new Date());
                                break;
                            }
                        }
                    }
                } else {
                    param.put("status", ScProductConstant.SC_TO_RECEIVE_FPDJS);//分配待接收状态
                    param.put("latestEndNodeId", order.getLatestEndNodeId());
                    param.put("latestEndNodeName", order.getLatestEndNodeName());
                    param.put("latestEndNodeTime", new Date());//设置最新更新节点时间
                }
            }else{
                if (param.containsKey("isNeedDispose") && "1".equals(param.get("isNeedDispose").toString())) {
                    param.put("status", ScProductConstant.SC_ORDER_OVER);//完结
                    List<Map> maps = productNodeDao.queryNodeListByNodeFolwIdWithOutSort(order.getNodeFlowId());
                    if (StringUtils.isNotEmpty(maps) && maps.size() > 0) {
                        for (Map nodeMap : maps) {
                            if ("完结".equals(nodeMap.get("name").toString())) {
                                param.put("latestEndNodeId", nodeMap.get("id"));
                                param.put("latestEndNodeName", nodeMap.get("name"));
                                param.put("latestEndNodeTime", new Date());//设置最新更新节点时间
                                param.put("completedTime", new Date());
                                break;
                            }
                        }
                    }
                } else {
                    param.put("status", ScProductConstant.SC_TO_RECEIVE_FPDJS);//分配待接收状态
                    param.put("latestEndNodeId", order.getLatestEndNodeId());
                    param.put("latestEndNodeName", order.getLatestEndNodeName());
                    param.put("latestEndNodeTime", new Date());//设置最新更新节点时间
                }

            }
            param.put("updaterId", currentUser.getId());
            param.put("updaterName", currentUser.getRealName() + currentUser.getLoginName());
            param.put("updaterOrgId", currentUser.getOrgId());
            param.put("updaterOrgName", map.get("name"));
            param.put("updateTime", new Date());
            param.put("originCode", ScProductConstant.ORDER_SOURCE_DISTRIBUTION);
            //保存协单人员 , 修改为不选默认清空
            if (StringUtils.isNotEmpty(param.get("assistIds"))) {
                zzInProcessService.updateAssist(id, param.get("assistIds").toString(), currentUser,map.get("type"));
            } else {
                zzInProcessService.updateAssist(id, "", currentUser,map.get("type"));
            }
            productOrderDao.distributionProductOrder(param);
                int i = DateUtils.compare_date(new Date(), timestatus.getDistributionEndTime());
                if (i == 1) {
                    timestatus.setDistributionTimeOutStatus(ScProductConstant.TIME_OUT);
                } else {
                    timestatus.setDistributionTimeOutStatus(timestatus.getDistributionTimeOutStatus());
                }
                timestatus.setReceiveStartTime(new Date());
                timestatus.setReceiveProcessTime(1);

                try {
                    timestatus.setReceiveTimeStatus(ScProductConstant.NORMAL);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                timestatus.setNodeTimeStatus(ScProductConstant.NORMAL);
                productTimeStatusDao.updateTimeOutStatus(timestatus);
            //插入操作记录
            SystemRecord record = new SystemRecord();
            record.setId(DggKeyWorker.nextId());//id
            record.setSource("2");
            record.setWorkTableName("zzsc_product_order");
            record.setWorkId(order.getId());
            record.setWorkNo(order.getScProductOrderNo());
            record.setBeOperaterId(receiverId);
            record.setOperateType("17");
            record.setRemarks("订单分配");
            systemRecordService.save(record, userEntity);
            // 如果无需处理添加完结记录
            if (param.containsKey("isNeedDispose") && "1".equals(param.get("isNeedDispose").toString())) {
                // 添加节点操作记录
                ProductNodeOperating scProductNodeOperating = new ProductNodeOperating();
                scProductNodeOperating.setId(DggKeyWorker.nextId());
                scProductNodeOperating.setRemarksType(1);   //(记录类型  1：节点更新，2：备注)
                scProductNodeOperating.setScProductOrderId(order.getId());
                scProductNodeOperating.setScProductOrderNo(order.getScProductOrderNo());
                scProductNodeOperating.setFlowOrgId(Long.parseLong(map.get("id").toString()));
                scProductNodeOperating.setFlowOrgName(map.get("name").toString());
                scProductNodeOperating.setFlowUserId(order.getFlowUserId());
                scProductNodeOperating.setFlowUserName(order.getFlowUserName());
                scProductNodeOperating.setOrderStatus(param.get("status").toString());
                scProductNodeOperating.setNodeId(param.get("latestEndNodeId").toString());
                scProductNodeOperating.setNodeName(param.get("latestEndNodeName").toString());
                scProductNodeOperating.setNodeProcessTimeType("2"); //节点办理类型
                scProductNodeOperating.setNodeOpetateTime(new Date());
                Map curOrg = commonMangerExtService.findOrg(userEntity.getOrgId());
                scProductNodeOperating.setCreaterOrgName(curOrg.get("name").toString());
                scProductNodeOperating.setRemark("订单无需办理完结" + (param.containsKey("lastRemark") && StringUtils.isNotEmpty(param.get("lastRemark")) ? ":" + param.get("lastRemark") : ""));
                scProductNodeOperating.setNodeTimeStatus(ScProductConstant.NORMAL); //节点超期状态
                scProductNodeOperating.setNodeProcessTime(0);
                scProductNodeOperating.setNodeStartTime(new Date());
                scProductNodeOperating.setNodeEndTime(new Date());
                scProductNodeOperating.setCreateUser(currentUser);
                productNodeOperatingDao.insert(scProductNodeOperating);

                SystemRecord records = new SystemRecord();
                records.setId(DggKeyWorker.nextId());//id
                records.setSource("2");
                records.setWorkTableName("zzsc_product_order");
                records.setWorkId(order.getId());
                records.setWorkNo(order.getScProductOrderNo());
                records.setBeOperaterId(receiverId);
                records.setOperateType("20");
                records.setRemarks(param.containsKey("lastRemark") && StringUtils.isNotEmpty(param.get("lastRemark")) ? param.get("lastRemark").toString() : "订单完结");
                systemRecordService.save(records, userEntity);
            }else{
                if(!StringUtils.isEmpty(order.getFlowContent())) {
                    List<Node> nodelist = flowService.getNode(id);
                    Node finishNode = flowService.queyNodeListById(order.getLatestEndNodeId() == null ? nodelist.get(0).getId().toString() : order.getLatestEndNodeId(), order.getId());
                    // 添加节点操作记录
                    ProductNodeOperating scProductNodeOperating = new ProductNodeOperating();
                    scProductNodeOperating.setId(DggKeyWorker.nextId());
                    scProductNodeOperating.setRemarksType(1);   //(记录类型  1：节点更新，2：备注)
                    scProductNodeOperating.setScProductOrderId(order.getId());
                    scProductNodeOperating.setScProductOrderNo(order.getScProductOrderNo());
                    scProductNodeOperating.setFlowOrgId(Long.parseLong(map.get("id").toString()));
                    scProductNodeOperating.setFlowOrgName(map.get("name").toString());
                    scProductNodeOperating.setFlowUserId(currentUser.getId());
                    scProductNodeOperating.setFlowUserName(currentUser.getRealName().concat(currentUser.getLoginName()));
                    scProductNodeOperating.setOrderStatus(param.get("status").toString());
                    scProductNodeOperating.setNodeId(order.getLatestEndNodeId());
                    scProductNodeOperating.setNodeName(order.getLatestEndNodeName());
                    scProductNodeOperating.setNodeProcessTimeType(finishNode.getIsNaturalorWorkday().toString()); //节点办理类型
                    scProductNodeOperating.setNodeOpetateTime(new Date());
                    scProductNodeOperating.setIsExtract(finishNode.getIsExtract());
                    Map curOrg = commonMangerExtService.findOrg(userEntity.getOrgId());
                    scProductNodeOperating.setCreaterOrgName(curOrg.get("name").toString());
                    scProductNodeOperating.setRemark("节点更新操作");
                    if (a == 1) {
                        scProductNodeOperating.setNodeTimeStatus(ScProductConstant.TIME_OUT); //节点超期状态
                    } else {
                        scProductNodeOperating.setNodeTimeStatus(ScProductConstant.NORMAL); //节点未超期状态
                    }
                    scProductNodeOperating.setNodeProcessTime((int) Math.ceil((double)finishNode.getHandleDate() / 24));
                    scProductNodeOperating.setNodeStartTime(nodeStartTime);
                    scProductNodeOperating.setNodeEndTime(nodeEndTime);
                    //佣金类型
                    scProductNodeOperating.setCommission(finishNode.getCommission());
                    //佣金金额
                    scProductNodeOperating.setBrokerage(finishNode.getBrokerage());
                    //保存更新节点数据
                    this.saveOpt(scProductNodeOperating, currentUser);
                    scProductNodeOperating.setCreateUser(currentUser);
                    productNodeOperatingDao.insert(scProductNodeOperating);
                }
            }
            try {// 发送消息 生产订单{0}已经于{1}分配给你，请及时确认处理！
                //通过MQ推送消息到UC
                CustomerRecord customerRecord = new CustomerRecord();
                customerRecord.setCustomerId(order.getCustomerId());
                customerRecord.setTableName("zzsc_product_order");
                customerRecord.setTableId(order.getId());
                customerRecord.setTableNo(order.getScProductOrderNo());
                customerRecord.setRemarkType(ScNoteType.ZZSC_NOTE_CODE5);
                customerRecord.setCreaterId(currentUser.getId());
                if (StringUtils.isNotEmpty(param.get("lastRemark"))){
                    customerRecord.setContent(param.get("lastRemark").toString());
                }
                MQMessageSendUtil.ucMessageSend(customerRecord);
                //提交之后，将订单信息同步到企大顺生产中心
                MQMessageSendUtil.qdsMessageSend(order, null,  currentUser);
                String[] msgs = new String[]{order.getScProductOrderNo(), DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss")};
                List<UserEntity> users = new ArrayList<>();
                users.add(userEntity);//接收人
                commonService.sendMsgByAsynchronous(users, msgs, "ZZSC_SC_ALLOT");//分配模板
                //发送企管家消息
                String conent="您好，您的客户"+order.getCustomerName()+"订单"+order.getOrderNo()+"办理的"+order.getScProductOrderNo()+"业务,分配节点已更新,请及时查看沟通";
                commonService.sendQgjMessage(order.getOrderId(),order.getBusinessTypeCode(),userEntity.getId(),userEntity.getRealName(),userEntity.getLoginName(),conent);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return "success";
        } else {
            return "分配失败,请联系管理员";
        }
    }

    /**
     * 订单备注
     *
     * @param param
     * @return
     */
    @SuppressWarnings("unchecked")
    @Transactional
    public String remarkOrder(Map param) {
        Long id = Long.parseLong(param.get("id").toString());
        ProductOrder order = productOrderDao.selectByPrimaryKey(id);
        UserEntity userEntity = sessionmanager.getCurrentUser();//当前操作人
        Map map = this.commonMangerExtService.findOrg(userEntity.getOrgId());
        if (null != map) {
            param.put("updaterId", userEntity.getId());
            param.put("updaterName", userEntity.getRealName());
            param.put("updaterOrgId", userEntity.getOrgId());
            param.put("updaterOrgName", map.get("name"));
            param.put("updateTime", new Date());
            param.put("lastRemarkTime", new Date());//最新备注时间
            param.put("lastRemark", param.get("order_remark").toString());
            param.put("lastUser", userEntity.getRealName()+" "+userEntity.getLoginName());
            productOrderDao.remarkOrder(param);
            //插入操作记录
            SystemRecord record = new SystemRecord();
            record.setId(DggKeyWorker.nextId());//id
            record.setSource("2");
            record.setWorkTableName("zzsc_product_order");
            record.setWorkId(order.getId());
            record.setWorkNo(order.getScProductOrderNo());
            record.setOperateType("20");
            record.setRemarks("订单备注：" + param.get("order_remark").toString());
            systemRecordService.save(record);
            String msgConent="您好，您的客户"+order.getCustomerName()+"订单"+order.getOrderNo()+"办理的"
                    +order.getScProductOrderNo()+"业务，添加一条备注信息，请及时查看";
            commonService.sendQgjMessage(order.getOrderId(),order.getBusinessTypeCode(),userEntity.getId(),userEntity.getRealName(),userEntity.getLoginName(),msgConent);
            try {
                //通过MQ推送消息到UC
                CustomerRecord customerRecord = new CustomerRecord();
                customerRecord.setCustomerId(order.getCustomerId());
                customerRecord.setTableName("zzsc_product_order");
                customerRecord.setTableId(order.getId());
                customerRecord.setTableNo(order.getScProductOrderNo());
                customerRecord.setRemarkType(ScNoteType.ZZSC_NOTE_CODE1);
                customerRecord.setCreaterId(userEntity.getId());
                if (StringUtils.isNotEmpty(param.get("order_remark"))){
                customerRecord.setContent(param.get("order_remark").toString());
                }
                MQMessageSendUtil.ucMessageSend(customerRecord);

                //提交之后，将订单信息同步到企大顺生产中心
                MQMessageSendUtil.qdsMessageSend(order, null,  userEntity);
            }catch (Exception e){
                e.printStackTrace();
            }
            return "success";
        } else {
            return "参数异常,备注失败";
        }
    }


    /**
     * <p>@Description 批量分配功能</p>
     * <p>@author mqy</p>
     * <p>@Time 2018/11/12 0012 15:59 创建时间</p>
     * <p>@return</p>
     */
    @Transactional
    public String distributionProductOrderList(Map param) {
        UserEntity curentUser = sessionmanager.getCurrentUser();//当前操作人
        String idStr = param.get("idStr").toString();
        String[] split = idStr.split(",");
        Long receiverId = Long.parseLong(param.get("receiverId").toString());//接收人ID
        String allotWay = param.get("allotWay").toString();//分配方式
        UserEntity userEntity = userservice.findUserById(receiverId);//查询接收人
        if (null == userEntity) {
            return "分配失败,未查询到接收人信息";
        }
        String nameAndLoginName = userEntity.getRealName() + userEntity.getLoginName();
        Long curentUserId = curentUser.getId();
        String curentUserName = curentUser.getRealName() + curentUser.getLoginName();
        Map map = this.commonMangerExtService.findOrg(userEntity.getOrgId());
        if (map == null) {
            return "分配失败,未查询到接收人部门信息";
        }
        if (split.length > 0) {
            //这些东西所有循环都一样,放一遍就可以了
            if (allotWay.equals(ScProductConstant.ALLOT_TO_PRODUCT_USER)) {//分配给负责人
                param.put("productUserId", receiverId);
                param.put("productUserName", nameAndLoginName);
                param.put("productUserOrgId", map.get("id"));
                param.put("productUserOrgName", map.get("name"));
            }else if(allotWay.equals(ScProductConstant.ALLOT_TO_PRODUCT_DEPT)){//分配给部门负责人
                param.put("deptHeadId", receiverId);
                param.put("deptHeadName", nameAndLoginName);
                param.put("deptHeadOrgId", map.get("id"));
                param.put("deptHeadOrgName", map.get("name"));
            }
            param.put("receiverId", receiverId);
            param.put("receiverName", nameAndLoginName);
            param.put("receiverOrgId", map.get("id"));
            param.put("receiverOrgName", map.get("name"));
            //为了保证异常订单正常工作, 分配的时候把流程人员写进去
            param.put("flowUserId", receiverId);
            param.put("flowUserName", nameAndLoginName);
            param.put("flowUserOrgId", map.get("id"));
            param.put("flowUserOrgName", map.get("name"));
            param.put("allotWay", allotWay);//分配方式
            param.put("allotUserId", curentUserId);
            param.put("allotUserName", curentUserName);
            param.put("allotUserOrgId", curentUserId);
            param.put("allotUserOrgName", map.get("name"));
            param.put("allotDate", new Date());//分配时间
            param.put("updaterId", curentUserId);
            param.put("updaterName", curentUserName);
            param.put("updaterOrgId", curentUser.getOrgId());
            param.put("updaterOrgName", map.get("name"));
            param.put("updateTime", new Date());
            param.put("originCode", ScProductConstant.ORDER_SOURCE_DISTRIBUTION);
            for (String ids : split) {
                Long id = Long.valueOf(ids);
                param.put("id", id);
                ProductOrder order = productOrderDao.selectByPrimaryKey(id);
                ProductTimeStatus timestatus = productTimeStatusDao.selectByPrimaryKey(order.getId());
                //保存节点开始结束时间
                Date nodeStartTime = null;
                Date nodeEndTime = null;
                //判断当前订单的分配方式 如果是部门分配需要重新计数超期时间，其他分配方式从超期计算表中取
                if("分配" != timestatus.getNodeName()){
                    nodeStartTime = order.getCreateTime();
                    if(!StringUtils.isEmpty(order.getFlowContent())){
                        //新流程
                        List<Node> nodelist = flowService.getNode(id);
                        if (nodelist.size() == 0) {
                            return "未配置流程！";
                        }
                        Node newNode = flowService.queyNodeListByName("分配", order.getId());
                        if(null != newNode.getName()) {
                            nodeEndTime = commonService.getDateFromStartByType(null == order.getLatestEndNodeTime() ? order.getUpdateTime() : order.getLatestEndNodeTime(),
                                    (int) Math.ceil((double)newNode.getHandleDate() / 24), (long) Math.ceil((double)newNode.getHandleDate() / 24) * 24 * 3600*1000,
                                    newNode.getIsNaturalorWorkday());
                            nodeEndTime =  DateUtils.getDate(DateUtils.dateString(nodeEndTime,"yyyy-MM-dd"),"yyyy-MM-dd");
                        }else{
                            nodeEndTime = commonService.getDateFromStartByType(order.getCreateTime(),
                                    1,  24l * 3600*1000,
                                    1);
                            nodeEndTime =  DateUtils.getDate(DateUtils.dateString(nodeEndTime,"yyyy-MM-dd"),"yyyy-MM-dd");
                        }
                    }else{
                        //老流程默认1个工作日
                        nodeEndTime = commonService.getDateFromStartByType(order.getCreateTime(),
                                1,  24l * 3600*1000,
                                1);
                        nodeEndTime =  DateUtils.getDate(DateUtils.dateString(nodeEndTime,"yyyy-MM-dd"),"yyyy-MM-dd");
                    }
                }else {
                    nodeStartTime = timestatus.getNodeStartTime();
                    nodeEndTime = timestatus.getNodeEndTime();
                }
                int a = DateUtils.compare_date(new Date(), nodeEndTime);
                //判断是否为原来流程
                if(!StringUtils.isEmpty(order.getFlowContent())) {
                    List<Node> nodelist = flowService.getNode(id);

                    //获取流程节点
                    if (nodelist.size() == 0) {
                        return "未配置流程！";
                    }
                    Node finishNode = flowService.queyNodeListByName("分配", order.getId());
                    if (null == timestatus.getNodeEndTime()) {
                        Date newDate = null;
                        //获取当前节点的配置的计算出的超期时间
                        newDate = commonService.getDateFromStartByType(new Date(),
                                    (int) Math.ceil((double)finishNode.getHandleDate() / 24), (long) Math.ceil((double)finishNode.getHandleDate() / 24) * 24 * 3600*1000,
                                    finishNode.getIsNaturalorWorkday());
                        newDate = DateUtils.getDate(DateUtils.dateString(newDate,"yyyy-MM-dd"),"yyyy-MM-dd");
                        timestatus.setNodeEndTime(newDate);
                    }
                    if (a == 1) {
                        if ((null == order.getPunishStatus() || 0 == order.getPunishStatus()) && null != timestatus.getNodeEndTime() && finishNode.getIsPunish()==1) {
                            Map currentMap = this.commonMangerExtService.findOrg(curentUser.getOrgId());
                            if (null != currentMap) {
                                order.setFlowUserId(curentUser.getId());
                                order.setFlowUserName(curentUser.getRealName().concat(curentUser.getLoginName()));
                                order.setFlowUserOrgId(Long.valueOf(currentMap.get("id").toString()));
                                order.setFlowUserOrgName(currentMap.get("name").toString());
                                Integer code = zzInProcessService.nodeTimeOutPunish(order, finishNode, timestatus);
                                if (code == 0) {
                                    if("成都资质事业部".equals(order.getProductOrgName())){
                                        //发送扣罚消息
                                        try {//不让影响其他功能
                                            List<UserEntity> users = new ArrayList<>();
                                            //扣罚人
                                            UserEntity user = userService.findUserById(order.getFlowUserId());
                                            users.add(user);
                                            //1.生产订单节点奖罚：您好，{生产订单编号}{客户名称}{订单产品}，xx节点超期产生扣罚，请查看确认。
                                            String msg[] = new String[]{order.getScProductOrderNo(),order.getCustomerName(),order.getProductName(),finishNode.getName()};
                                            commonService.sendMsgByAsynchronous(users, msg, "ZZSC_NODE_PUNISH_ALERT");//匹配模板
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                    }
                                    param.put("punishStatus", 0);
                                }
                            }
                        }
                    }
                    Node node = new Node();
                    if(nodelist.size()>0){
                        node = flowService.queyNodeListByName("接单", order.getId());
                        param.put("currentNodeId",node.getId());
                        param.put("currentNodeName",node.getName());
                    }
                    //写入下一个节点信息
                     Date date = new Date();
                    Integer hours = 0;
                    if (null != node) {
                        timestatus.setNodeId(node.getCode());
                        timestatus.setNodeName(node.getName());
                        hours = node.getHandleDate();
                        timestatus.setNodeProcessTimeType(node.getIsNaturalorWorkday());
                        timestatus.setNodeStartTime(date);
                        long millisecond = 0;
                        long Days = (long) Math.ceil((double)node.getHandleDate() / 24);
                        if (hours > 0) {
                            millisecond = Days * 24 * 3600*1000;
                        }

                        //获取当前节点的配置的计算出的超期时间
                        Date currentDate = null;
                            //获取当前节点的配置的计算出的超期时间
                            currentDate = commonService.getDateFromStartByType(new Date(),
                                    (int) Math.ceil((double)node.getHandleDate() / 24), millisecond,
                                    node.getIsNaturalorWorkday());
                            currentDate = DateUtils.getDate(DateUtils.dateString(currentDate,"yyyy-MM-dd"),"yyyy-MM-dd");
                        timestatus.setNodeEndTime(currentDate);
                        timestatus.setNodeProcessTime((int) Math.ceil((double)hours / 24));
                        timestatus.setNodeSuspendMillisecond(millisecond);
                        timestatus.setReceiveEndTime(currentDate);
                    }
                }
                //写入下一个节点
                if(StringUtils.isEmpty(order.getFlowContent())){
                    List<ProductNode> nodelist = zzInProcessService.queyNodeList(order.getNodeFlowId());
                    for (ProductNode scProductNode : nodelist) {
                        if (null != scProductNode.getName() && !"".equals(scProductNode.getName()) && "接单".equals(scProductNode.getName())) {
                            param.put("currentNodeId", scProductNode.getId());
                            param.put("currentNodeName", scProductNode.getName());
                        }
                    }

                }
                // 如果无需办理直接进入完结列表
                if(!StringUtils.isEmpty(order.getFlowContent())) {
                    List<Node> nodelist1 = flowService.getNode(id);
                    if (param.containsKey("isNeedDispose") && "1".equals(param.get("isNeedDispose").toString())) {
                        param.put("status", ScProductConstant.SC_ORDER_OVER);//完结
                            for (Node node1 : nodelist1) {
                                if ("完结".equals(node1.getName())) {
                                    param.put("latestEndNodeId", node1.getId());
                                    param.put("latestEndNodeName", node1.getName());
                                    param.put("latestEndNodeTime", new Date());//设置最新更新节点时间
                                    param.put("completedTime", new Date());
                                    break;
                                }
                            }
                    } else {
                        param.put("status", ScProductConstant.SC_TO_RECEIVE_FPDJS);//分配待接收状态
                        param.put("latestEndNodeId", order.getLatestEndNodeId());
                        param.put("latestEndNodeName", order.getLatestEndNodeName());
                        param.put("latestEndNodeTime", new Date());//设置最新更新节点时间
                    }
                }else{
                    if (param.containsKey("isNeedDispose") && "1".equals(param.get("isNeedDispose").toString())) {
                        param.put("status", ScProductConstant.SC_ORDER_OVER);//完结
                        List<Map> maps = productNodeDao.queryNodeListByNodeFolwIdWithOutSort(order.getNodeFlowId());
                        if (StringUtils.isNotEmpty(maps) && maps.size() > 0) {
                            for (Map nodeMap : maps) {
                                if ("完结".equals(nodeMap.get("name").toString())) {
                                    param.put("latestEndNodeId", nodeMap.get("id"));
                                    param.put("latestEndNodeName", nodeMap.get("name"));
                                    param.put("latestEndNodeTime", new Date());//设置最新更新节点时间
                                    param.put("completedTime", new Date());
                                    break;
                                }
                            }
                        }
                    } else {
                        param.put("status", ScProductConstant.SC_TO_RECEIVE_FPDJS);//分配待接收状态
                        param.put("latestEndNodeId", order.getLatestEndNodeId());
                        param.put("latestEndNodeName", order.getLatestEndNodeName());
                        param.put("latestEndNodeTime", new Date());//设置最新更新节点时间
                    }

                }
                if (!order.getStatus().equals(ScProductConstant.SC_TO_RECEIVE_XDDJS) && !order.getStatus().equals(ScProductConstant.SC_ORDER_BACK_TO_ALLOT)
                        && !order.getStatus().equals(ScProductConstant.SC_ORDER_WAIT_ALLOT)) {
                    //如果当前状态不是待分配状态或者事业部移交待分配,继续循环分配下一条
                    continue;
                }
                //保存协单人员
                if (StringUtils.isNotEmpty(param.get("assistIds"))) {
                    zzInProcessService.updateAssist(id, param.get("assistIds").toString(), curentUser,null);
                }

                productOrderDao.distributionProductOrder(param);
                long currentTime = System.currentTimeMillis() ;
                Date date=new Date(currentTime);

                //超期计算

                    int i = DateUtils.compare_date(new Date(), timestatus.getDistributionEndTime());
                    if (i == 1) {
                        timestatus.setDistributionTimeOutStatus(ScProductConstant.TIME_OUT);
                    } else {
                        timestatus.setDistributionTimeOutStatus(timestatus.getDistributionTimeOutStatus());
                    }
                    timestatus.setReceiveStartTime(new Date());
                    timestatus.setReceiveProcessTime(1);
                    try {

                        timestatus.setReceiveTimeStatus(ScProductConstant.NORMAL);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    timestatus.setNodeTimeStatus(ScProductConstant.NORMAL);
                    productTimeStatusDao.updateTimeOutStatus(timestatus);
                //插入操作记录
                SystemRecord record = new SystemRecord();
                record.setId(DggKeyWorker.nextId());//id
                record.setSource("2");
                record.setWorkTableName("zzsc_product_order");
                record.setWorkId(order.getId());
                record.setWorkNo(order.getScProductOrderNo());
                record.setBeOperaterId(receiverId);
                record.setOperateType("17");
                record.setRemarks("订单分配");
                systemRecordService.save(record, userEntity);

                //如果无需处理添加完结记录
                if (param.containsKey("isNeedDispose") && "1".equals(param.get("isNeedDispose").toString())) {
                    // 添加节点操作记录
                    ProductNodeOperating scProductNodeOperating = new ProductNodeOperating();
                    scProductNodeOperating.setId(DggKeyWorker.nextId());
                    scProductNodeOperating.setRemarksType(1);   //(记录类型  1：节点更新，2：备注)
                    scProductNodeOperating.setScProductOrderId(order.getId());
                    scProductNodeOperating.setScProductOrderNo(order.getScProductOrderNo());
                    scProductNodeOperating.setFlowOrgId(Long.parseLong(map.get("id").toString()));
                    scProductNodeOperating.setFlowOrgName(map.get("name").toString());
                    scProductNodeOperating.setFlowUserId(userEntity.getId());
                    scProductNodeOperating.setFlowUserName(userEntity.getRealName().concat(userEntity.getLoginName()));
                    scProductNodeOperating.setOrderStatus(param.get("status").toString());
                    scProductNodeOperating.setNodeId(param.get("latestEndNodeId").toString());
                    scProductNodeOperating.setNodeName(param.get("latestEndNodeName").toString());
                    scProductNodeOperating.setNodeProcessTimeType("2"); //节点办理类型
                    scProductNodeOperating.setNodeOpetateTime(new Date());
                    Map curOrg = commonMangerExtService.findOrg(userEntity.getOrgId());
                    scProductNodeOperating.setCreaterOrgName(curOrg.get("name").toString());
                    scProductNodeOperating.setRemark("订单无需办理完结" + (param.containsKey("lastRemark") && StringUtils.isNotEmpty(param.get("lastRemark")) ? ":" + param.get("lastRemark") : ""));
                    scProductNodeOperating.setNodeTimeStatus(ScProductConstant.NORMAL); //节点超期状态
                    scProductNodeOperating.setNodeProcessTime(0);
                    scProductNodeOperating.setNodeStartTime(new Date());
                    scProductNodeOperating.setNodeEndTime(new Date());
                    scProductNodeOperating.setCreateUser(curentUser);
                    productNodeOperatingDao.insert(scProductNodeOperating);

                    SystemRecord records = new SystemRecord();
                    records.setId(DggKeyWorker.nextId());//id
                    records.setSource("2");
                    records.setWorkTableName("zzsc_product_order");
                    records.setWorkId(order.getId());
                    records.setWorkNo(order.getScProductOrderNo());
                    records.setBeOperaterId(receiverId);
                    records.setOperateType("20");
                    records.setRemarks(param.containsKey("lastRemark") && StringUtils.isNotEmpty(param.get("lastRemark")) ? param.get("lastRemark").toString() : "订单完结");
                    systemRecordService.save(records, userEntity);
                }else{
                    // 添加节点操作记录
                    if(!StringUtils.isEmpty(order.getFlowContent())) {
                        List<Node> nodelist = flowService.getNode(id);
                        Node finishNode = flowService.queyNodeListById(order.getLatestEndNodeId() == null ? nodelist.get(0).getId() .toString(): order.getLatestEndNodeId(), order.getId());
                        ProductNodeOperating scProductNodeOperating = new ProductNodeOperating();
                        scProductNodeOperating.setId(DggKeyWorker.nextId());
                        scProductNodeOperating.setRemarksType(1);   //(记录类型  1：节点更新，2：备注)
                        scProductNodeOperating.setScProductOrderId(order.getId());
                        scProductNodeOperating.setScProductOrderNo(order.getScProductOrderNo());
                        scProductNodeOperating.setFlowOrgId(Long.parseLong(map.get("id").toString()));
                        scProductNodeOperating.setFlowOrgName(map.get("name").toString());
                        scProductNodeOperating.setFlowUserId(curentUserId);
                        scProductNodeOperating.setFlowUserName(curentUserName);
                        scProductNodeOperating.setOrderStatus(param.get("status").toString());
                        scProductNodeOperating.setNodeId(order.getLatestEndNodeId());
                        scProductNodeOperating.setNodeName(order.getLatestEndNodeName());
                        scProductNodeOperating.setNodeProcessTimeType(finishNode.getIsNaturalorWorkday().toString()); //节点办理类型
                        scProductNodeOperating.setNodeOpetateTime(new Date());
                        scProductNodeOperating.setIsExtract(finishNode.getIsExtract());
                        Map curOrg = commonMangerExtService.findOrg(userEntity.getOrgId());
                        scProductNodeOperating.setCreaterOrgName(curOrg.get("name").toString());
                        scProductNodeOperating.setRemark("节点更新操作");
                        if (a == 1) {
                            scProductNodeOperating.setNodeTimeStatus(ScProductConstant.TIME_OUT); //节点超期状态
                        } else {
                            scProductNodeOperating.setNodeTimeStatus(ScProductConstant.NORMAL); //节点未超期状态
                        }
                        scProductNodeOperating.setNodeProcessTime((int) Math.ceil(finishNode.getHandleDate() / 24));
                        scProductNodeOperating.setNodeStartTime(nodeStartTime);
                        scProductNodeOperating.setNodeEndTime(nodeEndTime);
                        scProductNodeOperating.setCreateUser(curentUser);
                        //佣金类型
                        scProductNodeOperating.setCommission(finishNode.getCommission());
                        //佣金金额
                        scProductNodeOperating.setBrokerage(finishNode.getBrokerage());
                        //保存更新节点数据
                        this.saveOpt(scProductNodeOperating, curentUser);
                        productNodeOperatingDao.insert(scProductNodeOperating);
                    }
                }

                try {// 发送消息 生产订单{0}已经于{1}分配给你，请及时确认处理！
                    //通过MQ推送消息到UC
                    CustomerRecord customerRecord = new CustomerRecord();
                    customerRecord.setCustomerId(order.getCustomerId());
                    customerRecord.setTableName("zzsc_product_order");
                    customerRecord.setTableId(order.getId());
                    customerRecord.setTableNo(order.getScProductOrderNo());
                    customerRecord.setRemarkType(ScNoteType.ZZSC_NOTE_CODE4);
                    customerRecord.setCreaterId(curentUser.getId());
                    if (StringUtils.isNotEmpty(param.get("lastRemark"))){
                        customerRecord.setContent(param.get("lastRemark").toString());
                    }
                    MQMessageSendUtil.ucMessageSend(customerRecord);

                    //提交之后，将订单信息同步到企大顺生产中心
                    MQMessageSendUtil.qdsMessageSend(order, null,  userEntity);

                    String[] msgs = new String[]{order.getScProductOrderNo(), DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss")};
                    List<UserEntity> users = new ArrayList<>();
                    users.add(userEntity);//接收人
                    commonService.sendMsgByAsynchronous(users, msgs, "ZZSC_SC_ALLOT");//分配模板
                    //发送企管家消息
                    String conent="您好，您的客户"+order.getCustomerName()+"订单"+order.getOrderNo()+"办理的"+order.getScProductOrderNo()+"业务分配节点已更新,请及时查看沟通";
                    commonService.sendQgjMessage(order.getOrderId(),order.getBusinessTypeCode(),userEntity.getId(),userEntity.getRealName(),
                            userEntity.getLoginName(),conent);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } else {
            return "分配失败,请刷新列表重试";
        }
        return "success";
    }
}
